package cn.wildfire.chat.app.main;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.BaseActivity;
import cn.wildfire.chat.app.extendsion.adapters.CountryCodesAdapter;
import cn.wildfire.chat.app.extendsion.classes.Region;
import cn.wildfire.chat.app.extendsion.classes.RegionRet;
import cn.wildfire.chat.app.extendsion.https.OkHttpRequest;
import cn.wildfire.chat.app.extendsion.https.ReqCallBack;
import cn.wildfire.chat.app.extendsion.https.ServerUrlClient;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;

/**
 * Create by HEKE, 2019/8/13 12:30
 * TODO 设置地区界面
 */
public class CountrySetActivity extends BaseActivity {

    @BindView(R2.id.contryListView)
    ListView contryListView;
    @BindView(R2.id.backImageView)
    ImageView backImageView;
    @BindView(R2.id.searEditText)
    EditText searEditText;
    @BindView(R2.id.searIcon)
    ImageView searIcon;
    @BindView(R2.id.searchContryListView)
    ListView searchContryListView;

    private String currentCode;
    private String regionId;

    // 国家选择
    private String[] countryArray;
    private String[] codes;
    private CountryCodesAdapter countryCodesAdapter;
    private CountryCodesAdapter searchCountryCodesAdapter;

    private RegionRet mRegionRet; // 服务器拉取国家及区号结果对象
    private Region mRegion; // 当前选择的国家信息对象

    @Override
    public void initViews() {
        setBarTitle(R.string.set_location);
        mRegionRet = getIntent().getParcelableExtra("RegionList");
        if (mRegionRet == null) {
            postRegionDatas();
        } else {
            loadRegions();
        }
        setLevel(3);
        searchCountryCodesAdapter = new CountryCodesAdapter(this, new ArrayList<>());
        searchContryListView.setAdapter(searchCountryCodesAdapter);
        searchContryListView.setOnItemClickListener(onSearchItemClickListener);
        searEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                search();
            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_country_set);
    }

    /**
     * 获取区号数据
     */
    private void postRegionDatas() {
        OkHttpRequest.getNewInstance(this).requestAsyn(ServerUrlClient.REGION, OkHttpRequest.TYPE_POST_JSON, null, new ReqCallBack<Object>() {
            @Override
            public void onReqSuccess(Object result) {
                try {
                    String ret = result.toString();
                    if (ret != null) {
                        RegionRet regionRet = new Gson().fromJson(ret, RegionRet.class);
                        if (regionRet != null) {
                            regionRet.regionArrayList = new ArrayList<>();
                            JSONArray array = new JSONObject(ret).getJSONArray("result");
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject object = array.getJSONObject(i);
                                Region region = new Gson().fromJson(object.toString(), Region.class);
                                regionRet.regionArrayList.add(region);
                            }
                            mRegionRet = regionRet;
                            loadRegions();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                Log.e("Get Region", "Error : " + errorMsg);
            }
        }).request();
    }

    /**
     * 加载显示国家区号
     */
    private void loadRegions() {
        if (mRegionRet == null)
            return;
        ArrayList<Region> regionArrayList = mRegionRet.getRegionArrayList();
        countryArray = new String[regionArrayList.size()];
        codes = new String[regionArrayList.size()];
        for (int i = 0; i < regionArrayList.size(); i++) {
            Region region = regionArrayList.get(i);
            countryArray[i] = region.regionName;
            codes[i] = region.regionCode;
        }
        countryCodesAdapter = new CountryCodesAdapter(this, mRegionRet.getRegionArrayList());
        contryListView.setAdapter(countryCodesAdapter);
        contryListView.setOnItemClickListener(onItemClickListener);
    }

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            try {
                Region region = (Region) countryCodesAdapter.getItem(position);
                currentCode = region.regionCode;
                regionId = "" + region.id;
                mRegion = region;
                doResult();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private AdapterView.OnItemClickListener onSearchItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            try {
                Region region = (Region) searchCountryCodesAdapter.getItem(position);
                currentCode = region.regionCode;
                regionId = "" + region.id;
                mRegion = region;
                doResult();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @OnClick({R2.id.backImageView})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.backImageView) {
            doResult();
        }
    }

    private void doResult() {
        Intent intent = new Intent();
        intent.putExtra("mRegion", mRegion);
        intent.putExtra("countryCode", currentCode);
        intent.putExtra("regionId", regionId);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        doResult();
    }

    @OnClick(R2.id.searIcon)
    public void onViewClicked() {
        search();
    }

    /**
     * 执行搜索
     */
    private void search() {
        try {
            String searchKey = searEditText.getText().toString();
            if (!TextUtils.isTextEmpty(searchKey)) {
                ArrayList<Region> searchResultList = new ArrayList<>();
                for (Region region : mRegionRet.getRegionArrayList()) {
                    if (region.regionName.contains(searchKey) || searchKey.contains(region.regionName) || region.regionName.equals(searchKey)
                            || region.regionCode.contains(searchKey) || searchKey.contains(region.regionCode) || searchKey.equals(region.regionCode)) {
                        searchResultList.add(region);
                    }
                }
                if (searchResultList.size() > 0) {
                    searchContryListView.setVisibility(View.VISIBLE);
                    contryListView.setVisibility(View.GONE);
                } else {
                    searchContryListView.setVisibility(View.GONE);
                    contryListView.setVisibility(View.VISIBLE);
                }
                searchCountryCodesAdapter.setRegionArrayList(searchResultList);
                searchCountryCodesAdapter.notifyDataSetChanged();
            } else {
                searchCountryCodesAdapter.setRegionArrayList(new ArrayList<>());
                searchCountryCodesAdapter.notifyDataSetChanged();
                searchContryListView.setVisibility(View.GONE);
                contryListView.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
